<?php

namespace App\Http\Middleware\Admin\v1;

use Closure;
use App\Models\Customer;
use App\Exceptions\ApiException;
use App\Exceptions\ApiErrCode;

class CreateApiKey
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $customer = Customer::where(['area'=>$request->area, 'phone'=>$request->phone])->first();
        if(!isset($customer)){  //该手机号码未注册
            throw new ApiException(ApiErrCode::PHONE_UNREGISTERED, trans('middleware.account_not_found'));
        }
        if(!in_array($request->type, [2,3])){    //管理员只创建按时间段计费和永久授权两种方案
            throw new ApiException(ApiErrCode::NOT_API_KEY_SCHEME, trans('middleware.api_key.not_api_key_scheme'));
        }
        $mid_params = ['customer_id' => $customer->id];
        $request->attributes->add($mid_params);
        return $next($request);
    }
}
